﻿namespace ChinaUnicom.Parser.Parsers
{
    using ChinaUnicom.Models;
    using HtmlAgilityPack;
    using System.Linq;

    internal class ProductParser : IItemsParser
    {
        public ItemType Type
        {
            get { return ItemType.Product; }
        }

        public ItemCollection Parse(string html)
        {
            ItemCollection items = new ItemCollection();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html.Replace("&nbsp;", string.Empty));

            HtmlNode contentContainer = doc.DocumentNode.Descendants("div")
                .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "nrong")
                .LastOrDefault();

            if (contentContainer != null)
            {
                Item item = null;
                foreach (HtmlNode node in contentContainer.ChildNodes)
                {
                    if (node.Name == "#text")
                    {
                        item = new Item();
                        item.Name = node.InnerText.InnerTextTrim();
                    }
                    else if (node.Name == "span")
                    {
                        item.Value = node.InnerText.InnerValueTrim();
                        items.Add(item);
                        item = null;
                    }
                }
            }

            return items;
        }
    }
}
